<template>
  <!-- 编辑资讯 -->
  <el-dialog
      v-model="state.visible"
      :title="props.type === 'add' ? '添加资讯信息' : '修改资讯信息'"
      width="600px"
      @close="clear"
      @open="show"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="标题" prop="title">
        <el-input v-model="state.ruleForm.title"  placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="简介"  prop="summary">
        <el-input v-model="state.ruleForm.summary" placeholder="请输入简介"></el-input>
      </el-form-item>
      <el-form-item label="封面" prop="cover">
        <el-upload
            :action="uploadImgServer"
            :on-success="handleUrlSuccess"
            list-type="picture"
            :auto-upload="true"
            :show-file-list="false"
        >
          <img v-if="state.ruleForm.cover" :src="state.ruleForm.cover" class="cover" alt="封面"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="分类">
        <el-select
            v-model="state.ruleForm.categoryId"
            placeholder="请选择分类"
            @click="handleOption"
            style="width: 170px"
            class="category-selector">
          <el-option
              v-for="category in state.categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <div id="editor"></div>
      </el-form-item>

      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
            v-model="state.ruleForm.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="state.visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </template>
  </el-dialog>
</template>


<script setup>

import {reactive, ref, nextTick} from 'vue'
import {useRoute} from 'vue-router'
import {getInfoNewsById, addInfoNews, updateInfoNews} from '../service/infoNewsApi.js'
import {getInfoCategoryById} from '../service/infoCategoryApi.js'
import {uploadImgServer} from "../store/index.js"
import {ElMessage} from 'element-plus'
import E from 'wangeditor'
import {fileUpload} from '../service/minioFileApi.js'
import {pageInfoCategory} from "../service/infoCategoryApi.js";

const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
})

// 获取分类列表数据
const handleOption = async () => {
  const params = {
    pageNum: 1,
    pageSize: 100,
    name: '',
  };
  const response = await pageInfoCategory(params);
  state.categoryList = response.data.records || []
};

//销毁富文本对象
const clear = () => {
  state.editor.destroy()
}
const show = () => {
  // 富文本编辑器实例创建

  state.editor = new E('#editor')
  //配置上传地址

  // 配置服务器端地址
  state.editor.config.uploadImgServer = uploadImgServer
  state.editor.config.uploadFileName = 'file'
  state.editor.config.uploadImgHooks = {
    customInsert: (insertImgFn, result) => {

      const imgUrl = result.data;
      insertImgFn(imgUrl); // 插入图片
    },
    // 可选：错误处理
    error: (error) => {
      console.error('上传失败:', error);
    }
  };
  // state.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
  //   const response = await fileUpload(resultFiles[0]);
  //   insertImgFn(response.data)
  // }
  state.editor.config.menus = [
    // 菜单配置
    'head', // 标题
    'bold', // 粗体
    'italic', // 斜体
    'underline', // 下划线
    'link', // 插入链接
    'image', // 插入图片
    'undo', // 撤销
    'redo' // 重复
  ]
  state.editor.create()

}
const formRef = ref(null)
const route = useRoute()
const filelist = ref([])

const state = reactive({
  editor: null,
  visible: false,
  categoryLevel: 1,
  parentId: 0,
  ruleForm: {
    id: '',
    name: '',
    cover: '',
    summary: '',
    content: '',
    title: '',
    publishTime: '',
    categoryId: '',
    categoryName: '',
    viewCount: ''
  },
  rules: {
    title: [
      {required: true, message: '标题不能为空', trigger: ['change']}
    ],
    summary: [
      {required: true, message: '简介不能为空', trigger: ['change']}
    ],
    cover: [
      {required: true, message: '封面不能为空', trigger: ['change']}
    ],
    categoryId: [
      {required: true, message: '分类不能为空', trigger: ['change']}
    ],
  },
})
// 获取详情
const getDetail = async (id) => {
  const result = await getInfoNewsById(id);
  // 回显表单数据
  state.ruleForm = {
    id: result.data.id,
    title: result.data.title,
    cover: result.data.cover,
    summary: result.data.summary,
    content: result.data.content,
    publishTime: result.data.publishTime,
    categoryName: result.data.categoryName,
  }
  await getCurrentCategoryName(result.data.categoryId)
  if (state.editor != null) {
    state.editor.txt.html(result.data.content)
  }
}

// 获取当前数据的分类名称
const getCurrentCategoryName = async (id) => {
  const result = await getInfoCategoryById(id)
  if (result.code === 200) {
    state.ruleForm.categoryId = result.data.id
    state.ruleForm.categoryName = result.data.name
  }
}

//上传成功
const handleUrlSuccess = (res) => {
  state.ruleForm.cover = res.data
}

// 开启弹窗
const open = (id) => {
  state.visible = true
  if (id) {
    state.ruleForm.id = id
    // 如果是有 id 传入，证明是修改模式
    getDetail(id)
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id
    const {level = 1, parent_id = 0} = route.query
    state.ruleForm = {
      id: '',
      name: '',
      cover: '',
      title: '',
      summary: '',
      content: '',
      categoryId: '',
      publishTime:''
    }
    state.parentId = parent_id
    state.categoryLevel = level
  }

}

// 关闭弹窗
const close = () => {
  state.visible = false;
}
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 将内容以html的形式拉下来
      state.ruleForm.content = state.editor.txt.html();

      // 构建请求参数
      const params = {
        title: state.ruleForm.title,
        cover: state.ruleForm.cover,
        summary: state.ruleForm.summary,
        content: state.ruleForm.content,
        categoryId: state.ruleForm.categoryId,
        publishTime :state.ruleForm.publishTime
      };

      if (props.type === 'add') {
        try {
          await addInfoNews(params);
          ElMessage.success('添加成功');
          close();
          if (props.reload) props.reload();
        } catch (error) {
          console.error('添加失败:', error);
          ElMessage.error('添加失败');
        }
      } else {
        params.id = state.ruleForm.id;
        try {
          await updateInfoNews(params);
          ElMessage.success('修改成功');
          close();
          if (props.reload) props.reload();
        } catch (error) {
          console.error('修改失败:', error);
          ElMessage.error('修改失败');
        }
      }
    }
  });
};

defineExpose({open, close})
</script>

<style scoped>
.el-upload__tip {
  float: left;
}

.cover {
  border: 1px solid #FFFFFF;
  border-radius: 10px;
  width: 80px;
  height: 80px;
}
</style>